package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.util.FileUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
/*
    @Value("${reggie.path}")
    private String basePath;

     *//**
     * 文件上传
     *
     * @param file
     * @return
     *//*
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        try {
            //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            //重命名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString() + substring;

            //对文件上传目录进行判断
            File f = new File(basePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            //转存文件
            file.transferTo(new File(basePath + fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败:" + e.getMessage());
        }
    }

    */
    /**
     * 文件下载
     *
     * @param name
     * @param response
     *//*
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //读取磁盘文件 输入流
            FileInputStream fis = new FileInputStream(basePath + name);

            //获取响应字节 输出流
            ServletOutputStream sos = response.getOutputStream();

            //IO对拷
            IOUtils.copy(fis, sos);

            //释放资源
            sos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    */

    @Autowired
    private FileUploader fileUploader;

    /**
     * Minio整合步骤 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String fileName = null;
        try {
            fileName = fileUploader.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

}
